package controller

import (
	"github.com/gin-gonic/gin"
	"niu-video/app/model"
	"niu-video/app/service"
	"niu-video/pkg/response"
	"niu-video/pkg/validate"
	"strconv"
)

type UserController struct {
}

// Login 登录
func (ctrl *UserController) Login(c *gin.Context) {

	request := model.LoginRequest{}
	if ok := validate.Validate(c, &request); !ok {
		return
	}
	token, err := service.UserService.Login(request)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithDetailed(token, "登录成功！", c)
}

// Register 注册
func (ctrl *UserController) Register(c *gin.Context) {

	request := model.RegisterRequest{}
	if ok := validate.Validate(c, &request); !ok {
		return
	}
	err := service.UserService.Register(request)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("注册成功！", c)
}

// Info 获得个人信息
func (ctrl *UserController) Info(c *gin.Context) {
	userId := c.GetInt64("current_user_id")
	author, err := service.UserService.Info(userId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(author, c)
}

// Reset 修改密码
func (ctrl *UserController) Reset(c *gin.Context) {
	request := model.ResetRequest{}
	if ok := validate.Validate(c, &request); !ok {
		return
	}
	msg, err := service.UserService.Reset(request)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage(msg, c)
}

// Get 获取用户信息
func (ctrl *UserController) Get(c *gin.Context) {
	selfUserId := c.GetInt64("current_user_id")
	userId_ := c.Query("userId")
	userId, err := strconv.ParseInt(userId_, 10, 64)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	authorVo, err := service.UserService.Get(userId, selfUserId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(authorVo, c)
}

func (ctrl *UserController) Update(c *gin.Context) {
	selfUserId := c.GetInt64("current_user_id")
	request := model.UpdateUserInfoRequest{}
	if ok := validate.Validate(c, &request); !ok {
		return
	}
	err := service.UserService.Update(request, selfUserId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}

// Action
//
//	@Description: 用户的行为操作，可以用来推荐
//	@receiver ctrl
//	@param c
func (ctrl *UserController) Action(c *gin.Context) {
	selfUserId := c.GetInt64("current_user_id")
	request := model.UserAction{}
	if ok := validate.Validate(c, &request); !ok {
		return
	}
	service.UserService.UserAction(request, selfUserId)
	response.Ok(c)
}
